import axios from "axios";
// import Vue from "vue";
import { Dialog } from "vant";
// 查询字符串转成对象
import qs from "qs";
import router from "./router/index";

// 请求拦截器
axios.interceptors.request.use(
  config => {
    console.log("axios请求进入拦截器------");
    /**
     * axios发post请求时接受不了对象形式的参数
     * 解决方法
     * this.axios.post(
     *  'user/signin',
     *  qs.stringify({uname:dingding,upwd:123456})
     * )
     */
    if (config.method === "post") {
      config.data = qs.stringify(config.data);
    }
    if (localStorage.getItem("token")) {
      config.headers.Authorization = localStorage.getItem("token");
    }
    if (sessionStorage.getItem("token")) {
      config.headers.Authorization = sessionStorage.getItem("token");
    }
    console.log(
      "永久保存：" + localStorage.getItem("token"),
      "保存本地：" + sessionStorage.getItem("token")
    );

    return config;
  },
  error => {
    // Do something with request error
    return Promise.reject(error);
  }
);
// 响应拦截器
axios.interceptors.response.use(res => {
  console.log(res);
  console.log("触发拦截器----");
  // console.log(res);
  // const that = this;
  // 600表示token失效
  if (res.data.code == 600) {
    localStorage.removeItem("token");
    sessionStorage.removeItem("token");

    localStorage.removeItem("img");
    localStorage.removeItem("userName");

    router.push("/AuthCode");
  } else if (res.data.code == 500) {
    Dialog.alert({
      message: res.data.msg
      // theme: "round-button",
    }).then(() => {
      // on close
    });
    // router.push("/AuthCode");
  } else if (res.data.msg.token) {
    localStorage.setItem("token", res.data.msg.token);
    sessionStorage.setItem("token", res.data.msg.token);
  }

  return res;
});

export default {
  components: {
    [Dialog.Component.name]: Dialog.Component
  },
  install: function(Vue) {
    Vue.prototype.axios = axios;
  }
};
